package com.quick.proxy.server.handler;

import com.quick.proxy.core.handler.ProxyChannelInboundHandlerAdapter;
import com.quick.proxy.core.utils.ProxyUtils;
import com.quick.proxy.server.ProxyResources;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * Description: 连接处理程序
 * Author: 吃素不吃肉
 * Date: 2023/7/9
 *
 * @author 吃素不吃肉
 */
@Component
@Sharable
@Slf4j
public class ConnectHandler extends ProxyChannelInboundHandlerAdapter {
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        log.error("ip[{}]proxy server error.", ProxyUtils.getRemoteAddress(ctx.channel()), cause);
    }

    /**
     * 客户端去和服务端连接成功时触发
     *
     * @param ctx 上下文
     * @throws Exception 异常
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        String remoteAddress = ProxyUtils.getRemoteAddress(ctx.channel());
        log.info("client address {}", remoteAddress);
        //通道关闭监听
        ctx.channel().closeFuture().addListener((ChannelFuture future) -> {
            //清理资源
            ProxyResources.clearProxyResources(future.channel());
        });
        super.channelActive(ctx);
    }

    /**
     * 客户端去和服务端失去连接时触发
     *
     * @param ctx 上下文
     * @throws Exception 异常
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        if (ctx.channel().isOpen()) {
            //关闭代理通道
            ctx.channel().close();
        }
        super.channelInactive(ctx);
    }
}
